package com.getpebble.android.notifications.util;

import android.annotation.TargetApi;
import android.app.ActivityManager;
import android.app.ActivityManager.RunningServiceInfo;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.pm.PackageManager;
import android.provider.Settings.Secure;
import android.support.v4.app.NotificationCompat.BigTextStyle;
import android.support.v4.app.NotificationCompat.Builder;
import com.getpebble.android.R;
import com.getpebble.android.common.core.trace.Trace;
import com.getpebble.android.common.core.util.PblPreferences;
import com.getpebble.android.common.core.util.PblPreferences.PrefKey;
import com.getpebble.android.main.activity.MainActivity;
import com.getpebble.android.notifications.PblNotificationService;
import java.util.List;

public class NotificationServiceUtil {
    public static final String TAG = NotificationServiceUtil.class.getSimpleName();
    private static int sKnownGoodCrashCount = 0;
    private static int sLastReportedCrashCount = 0;

    static void verifyNotificationListenerService(Context context) throws IllegalArgumentException {
        if (context == null) {
            throw new IllegalArgumentException("'context' cannot be null!");
        } else if (isNotificationListenerServiceCrashed(context)) {
            onNotificationListenerDead(context);
        }
    }

    private static void onNotificationListenerDead(Context context) {
        if (context == null) {
            Trace.warning(TAG, "onNotificationListenerDead: Context is null");
        } else if (new PblPreferences(context).getBooleanData(PrefKey.ONBOARDING_COMPLETED, false) && isNotificationListenerServiceEnabled(context)) {
            displayDeadListenerNotification(context);
            ComponentName componentName = new ComponentName(context, PblNotificationService.class);
            PackageManager packageManager = context.getPackageManager();
            if (packageManager != null) {
                Trace.debug(TAG, "Package manager is not null; toggling listener state");
                packageManager.setComponentEnabledSetting(componentName, 2, 1);
                packageManager.setComponentEnabledSetting(componentName, 1, 1);
            }
        }
    }

    private static void displayDeadListenerNotification(Context context) {
        if (context == null) {
            Trace.error(TAG, "Couldn't display dead listener notification: context was null");
            return;
        }
        NotificationManager notificationManager = (NotificationManager) context.getSystemService("notification");
        PendingIntent contentIntent = PendingIntent.getActivity(context, 0, new Intent(context, MainActivity.class), 0);
        Builder builder = new Builder(context);
        builder.setContentTitle(context.getString(R.string.notification_listener_dead_title));
        builder.setContentText(context.getString(R.string.notification_listener_dead_message));
        builder.setContentIntent(contentIntent);
        builder.setSmallIcon(R.connected_status_bar);
        builder.setStyle(new BigTextStyle().bigText(context.getString(R.string.notification_listener_dead_message)));
        builder.setWhen(System.currentTimeMillis());
        notificationManager.notify(0, builder.build());
    }

    @TargetApi(18)
    static void startNotificationListenerSettingsActivity(Context context) {
        SharedPreferences sp = PblPreferences.getSharedPreferences(context);
        context.startActivity(new Intent("android.settings.ACTION_NOTIFICATION_LISTENER_SETTINGS"));
        Editor editor = sp.edit();
        editor.putBoolean("nag_enable_service", true);
        editor.apply();
    }

    static boolean isNotificationListenerServiceEnabled(Context context) throws IllegalArgumentException {
        if (context == null) {
            throw new IllegalArgumentException("'context' cannot be null!");
        }
        String enabledNotificationListeners = Secure.getString(context.getContentResolver(), "enabled_notification_listeners");
        return enabledNotificationListeners != null && enabledNotificationListeners.contains(context.getPackageName() + "/");
    }

    public static void receivedNotificationFromListenerService() {
        sKnownGoodCrashCount = sLastReportedCrashCount;
    }

    private static boolean isNotificationListenerServiceCrashed(Context context) throws IllegalArgumentException {
        if (context == null) {
            throw new IllegalArgumentException("'context' cannot be null!");
        }
        List<RunningServiceInfo> runningServiceInfo = ((ActivityManager) context.getSystemService("activity")).getRunningServices(Integer.MAX_VALUE);
        if (runningServiceInfo == null) {
            return true;
        }
        for (RunningServiceInfo service : runningServiceInfo) {
            if (PblNotificationService.class.getName().equals(service.service.getClassName())) {
                sLastReportedCrashCount = service.crashCount;
                Trace.info(TAG, "crash count = " + sLastReportedCrashCount + " known good crash count = " + sKnownGoodCrashCount);
                if (service.crashCount > sKnownGoodCrashCount) {
                    return true;
                }
                return false;
            }
        }
        return true;
    }
}
